package br.com.ordersys.framework.db;

import java.util.HashMap;
import java.util.Map;

import br.com.ordersys.framework.db.metadata.TableMetadata;

public class DAORegistry {
	public static Map<String,Domain> domains = new HashMap<String, DAORegistry.Domain>();

	public static DAO getDAO(String entityName) {
		String currentDomain = DataSourceFactory.getSingleton().getTenantIdentifier();
		
		if(currentDomain ==  null) {
			currentDomain = "$main.data.domain";
		}
		
		return getDAO(entityName,currentDomain);
	}
		
	public static DAO getDAO(String entityName, String domainName) {
		Domain d = domains.get(domainName);
		
		if(d == null) {
			d = new Domain(entityName);
			domains.put(domainName, d);
		}
		
		return d.getDAO(entityName);
	}
	
	private static class Domain{
		Map<String,DAO> daos;
		String name;
		
		Domain(String name){
			this.name = name;
			daos = new HashMap<String, DAO>();
		}
		
		DAO getDAO(String entityName) {
			DAO dao = daos.get(entityName);
			
			if(dao == null) {
				dao = buildDAO(entityName);
				daos.put(entityName, dao);
			}
			
			return dao;
		}

		private DAO buildDAO(String entityName) {
			TableMetadata tmd = DataSourceFactory.getSingleton().resolveTable(entityName);
			
			DAO dao = new DAO(tmd,name);
			
			return dao;
		}
	}
}
